<template>
  <el-dialog :title="`${isEdit ? '修改' : '添加'}事业部评价`" :visible.sync="show" :close-on-click-modal="false" :show-close="!btnLoading" width="1200px" @closed="closed">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item prop="prjchkId" class="hide" />
      <el-row :gutter="10" style="display: flex;flex-wrap: wrap;">
        <el-col :span="8">
          <el-form-item label="项目" prop="projectId">
            <el-select v-model="form.projectId" placeholder="请选择项目" :disabled="isEdit" filterable clearable :loading="prjLoading" style="width: 100%" @change="onChangeProject">
              <el-option v-for="project in projectList" :key="project.fid" :label="project.cflastname" :value="project.fid" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="rdcTypeList.length">
          <el-form-item label="检查单位" prop="rdcType" key="rdcType" :rules="rules.rdcType">
            <el-select v-model="form.rdcType" placeholder="请选择检查单位" :disabled="isEdit" style="width: 100%">
              <el-option v-for="dict in rdcTypeList" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检查日期" prop="checkDate">
            <el-date-picker v-model="form.checkDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" style="width: 100%" />
          </el-form-item>
        </el-col>
        <!--<el-col :span="8" v-if="tradeTypeList.length">
          <el-form-item label="操盘类型" prop="tradeType" key="tradeType">
            <el-select v-model="form.tradeType" :placeholder="isEdit ? '无' : '请选择操盘类型'" :disabled="isEdit" clearable style="width: 100%">
              <el-option v-for="dict in tradeTypeList" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>-->
        <el-col :span="8">
          <el-form-item label="项目(检查口径)" prop="inpectionCaliber"><el-input v-model.trim="form.inpectionCaliber" placeholder="请输入检查球号对应名称" :maxlength="255" /></el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目总" prop="xmzName">
            <el-input class="fake-selector input-width" readonly v-model="form.xmzName" auto-complete="off" placeholder="请选择项目总" @click.native="openSelectUser('xmzId', 'xmzName', true)">
              <i slot="append" class="el-icon-arrow-down" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目经理" prop="xmjlName">
            <el-input class="fake-selector input-width" readonly v-model="form.xmjlName" auto-complete="off" placeholder="请选择项目经理" @click.native="openSelectUser('xmjlId', 'xmjlName', true)">
              <i slot="append" class="el-icon-arrow-down" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目工程负责人" prop="xmPrincipalName">
            <el-input class="fake-selector" readonly v-model="form.xmPrincipalName" placeholder="请选择项目工程负责人" @click.native="openSelectUser('xmPrincipalId', 'xmPrincipalName', true)">
              <i slot="append" class="el-icon-arrow-down" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="集群分管领导" prop="colonyName">
            <el-input class="fake-selector input-width" readonly v-model="form.colonyName" auto-complete="off" placeholder="请选择集群分管领导" @click.native="openSelectUser('colonyId', 'colonyName', true)">
              <i slot="append" class="el-icon-arrow-down" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="事业部分管领导" prop="businessName">
            <el-input class="fake-selector input-width" readonly v-model="form.businessName" auto-complete="off" placeholder="请选择事业部分管领导" @click.native="openSelectUser('businessId', 'businessName', true)">
              <i slot="append" class="el-icon-arrow-down" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="施工单位" prop="constructionId">
            <el-select v-model="form.constructionId" placeholder="请选择施工单位" filterable multiple collapse-tags clearable :loading="constructionLoading" class="optimized-select" @change="onChangeConstructionId">
              <el-option v-for="item in constructionList" :key="item.constructionId" :label="item.constructionName" :value="item.constructionId" />
              <el-option value="" @click.native="showEditRdcConstruction = true">
                <el-button size="mini" type="text" icon="el-icon-plus">添加施工单位</el-button>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="施工单位负责人" prop="constructionUser"><el-input v-model.trim="form.constructionUser" placeholder="请输入施工单位负责人" :maxlength="255" /></el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="描述" prop="description"><el-input v-model="form.description" type="textarea" placeholder="请输入内容" :maxlength="500" /></el-form-item>
    </el-form>

    <el-divider>检查项录入</el-divider>
    <!--<InputMode ref="InputMode" v-model="form.scores" :cfg="filteredCfgInfo" />-->
    <score-list ref="listScoreRef" :project-id="form.projectId" />
    <div slot="footer">
      <el-button type="primary" :loading="btnLoading" @click="btnSubmit">确 定</el-button>
      <el-button :disabled="btnLoading" @click="show = false">取 消</el-button>
    </div>
    <!-- 选择人员 -->
    <select-user-dialog :show.sync="showSelectUserVisible" :selected="selectedUser" :multi="selectUserOption.multi" :max-num="5" @select="selectUserCallback" />
    <!-- 编辑施工单位 -->
    <EditRdcConstruction ref="EditRdcConstruction" v-model="showEditRdcConstruction" @ok="getConstructionList" />
    <SimilarDataConfirm ref="SimilarDataConfirm" @confirm="btnSubmit({ isRepeatEntry: 'allow' })" />
  </el-dialog>
</template>
<script>
// 添加或修改检查项得分
import { editFormMixin } from '@/utils/mixin'
import { selectProjectExcludeCfProjectStage } from '@/api/baseManage/project'
import { saveScores } from '@/api/checkScore/cqEval'
import { listRdcConstruction } from '@/api/qualityManage/cq'
import EditRdcConstruction from '@/views/cq/components/EditRdcConstruction'
// import InputMode from '../chkitemScore/InputMode'
// import { matchingRule } from '../chkitemScore/common'
import SelectUserDialog from '@/views/components/SelectUserDialog.vue'
import scoreList from './scoreList'
import SimilarDataConfirm from './SimilarDataConfirm'

export default {
  components: { SelectUserDialog, scoreList, EditRdcConstruction, SimilarDataConfirm },
  mixins: [editFormMixin],
  dicts: ['cq_eval_rdc_type', 'cq_trade_type'],
  data() {
    return {
      primaryKey: 'prjchkId',
      form: {
        prjchkId: '',
        versionId: '',
        versionCode: '',
        chkitemCode: new Date(),
        landparcelId: '',
        projectId: '',
        projectType: '',
        rdcType: '',
        tradeType: '',
        inpectionCaliber: '',
        deliveryTypes: '',
        checkDate: new Date(),
        constructionId: [], // 施工单位
        constructionName: '',
        constructionUser: '',
        description: '',
        xmzId: '',
        xmzName: '',
        xmPrincipalId: '',
        xmPrincipalName: '',
        xmjlId: '',
        xmjlName: '',
        colonyId: '',
        colonyName: '',
        businessId: '',
        businessName: '',
        scores: []
      },
      rules: {
        projectId: [{ required: true, message: '请选择项目' }],
        rdcType: [{ required: true, message: '请选择检查单位' }],
        checkDate: [{ required: true, message: '请选择日期' }]
      },
      prjLoading: false,
      projectList: [],
      cfgInfo: {},
      evalScore: {},
      // 选择用户窗口
      showSelectUserVisible: false,
      selectUserOption: { idField: '', nameField: '', multi: false },
      selectedUser: [],
      businessScore: {},
      constructionLoading: false,
      constructionList: [], // 施工单位
      showEditRdcConstruction: false // 添加施工单位的弹窗
    }
  },
  computed: {
    isEdit() {
      return !!this.form.prjchkId
    },
    rdcTypeList() {
      // 检查单位列表
      const list = this.dict?.type.cq_eval_rdc_type || []
      const rdcType = this.cfgInfo.rdcType || ''
      if (!rdcType || !list.length) return []

      const rdcTypes = rdcType.split(',').filter(i => i)
      return list.filter(i => rdcTypes.includes(i.value))
    },
    tradeTypeList() {
      // 操盘类型列表
      const list = this.dict?.type.cq_trade_type || []
      const tradeType = this.cfgInfo.tradeType || ''
      if (!tradeType || !list.length) return []

      const tradeTypes = tradeType.split(',').filter(i => i)
      return list.filter(i => tradeTypes.includes(i.value))
    },
    filteredCfgInfo() {
      // 根据选中的操盘类型过滤子项
      const { cfgInfo } = this
      const { tradeType } = this.form
      if (!cfgInfo.children?.length || !tradeType) return cfgInfo

      const info = JSON.parse(JSON.stringify(cfgInfo))
      info.children = info.children.filter(i => {
        const str = i.tradeType || ''
        if (!str) return false
        const arr = str.split(',').filter(i => i)
        return arr.includes(tradeType)
      })
      return info
    }
  },
  created() {
    this.getAuthUserProjectList()
  },
  methods: {
    // 获取施工单位
    async getConstructionList() {
      this.constructionLoading = true
      const res = await listRdcConstruction().catch(() => false)
      this.constructionLoading = false
      if (res === false) return
      this.constructionList = res.data || []
    },
    // 施工单位改变时，手动赋值 constructionName
    onChangeConstructionId(ids) {
      if (!ids) return (this.form.constructionName = '')
      const list = this.constructionList || []
      const names = []
      ids.forEach(id => {
        const item = list.find(i => i.constructionId === id)
        if (item && item.constructionName) {
          names.push(item.constructionName)
        }
      })
      this.form.constructionName = names.join(',')
    },
    // 打开选择用户
    openSelectUser(idField, nameField, multi) {
      this.selectUserOption = { idField, nameField, multi: !!multi }
      let selectedUser = []
      const idValue = this.form[idField] || ''
      const nameValue = this.form[nameField] || ''
      const ids = idValue ? idValue.split(',') : []
      const names = nameValue ? nameValue.split(',') : []
      if (ids.length && names.length) {
        selectedUser = ids.map((id, index) => ({ value: id, label: names[index] }))
      }
      this.selectedUser = selectedUser
      this.showSelectUserVisible = true
    },
    closed() {
      this.$refs.form.resetFields()
      this.form = {
        prjchkId: '',
        versionId: '',
        versionCode: '',
        chkitemCode: '',
        landparcelId: '',
        projectId: '',
        projectType: '',
        rdcType: '',
        tradeType: '',
        inpectionCaliber: '',
        deliveryTypes: '',
        checkDate: new Date(),
        constructionId: [], // 施工单位
        constructionName: '',
        constructionUser: '',
        description: '',
        xmzId: '',
        xmzName: '',
        xmPrincipalId: '',
        xmPrincipalName: '',
        xmjlId: '',
        xmjlName: '',
        colonyId: '',
        colonyName: '',
        businessId: '',
        businessName: '',
        scores: []
      }
      this.cfgInfo = {}
      this.evalScore = {}
    },
    opened(item = {}, { cfgInfo }) {
      this.evalScore = JSON.parse(JSON.stringify(item))
      this.cfgInfo = JSON.parse(JSON.stringify(cfgInfo))
      this.$refs.listScoreRef.init(item, cfgInfo)
      if (item.constructionId) {
        this.form.constructionId = item.constructionId.split(',')
      }
      this.getConstructionList()
      if (!this.projectList.length) this.getAuthUserProjectList()
    },
    // 选择用户回调
    selectUserCallback(selection) {
      const { idField, nameField } = this.selectUserOption
      this.form[idField] = selection.map(i => i.value).join(',')
      this.form[nameField] = selection.map(i => i.label).join(',')
    },
    // 获取授权的用户的项目列表
    async getAuthUserProjectList() {
      this.prjLoading = true
      const res = await selectProjectExcludeCfProjectStage({ needUserId: false }).catch(() => false)
      this.prjLoading = false
      if (res === false) return
      this.projectList = res.data || []
    },
    onChangeProject() {
      this.changeXmPrincipal()
    },
    changeXmPrincipal() {
      // 改变项目时，若有 项目总、项目工程负责人、项目经理，则覆盖现有值
      const { projectId } = this.form
      if (!projectId) return

      const list = this.projectList
      const data = list.find(i => i.fid === projectId)
      if (!data) return

      if (data.xmzFids) {
        this.form.xmzId = data.xmzFids
        this.form.xmzName = data.xmzName
      }
      if (data.principalIds) {
        this.form.xmPrincipalId = data.principalIds
        this.form.xmPrincipalName = data.principalNames
      }
      if (data.xmjlId) {
        this.form.xmjlId = data.xmjlId
        this.form.xmjlName = data.xmjlName
      }
    },
    async onSubmit(opts) {
      const { cfgInfo } = this
      const valid = await this.$refs.form.validate().catch(() => false)
      const listValid = this.$refs.listScoreRef.getValidate()
      if (!valid || !listValid) return
      // const validScores = await this.$refs.InputMode.validate().catch(() => false)
      // if (!validScores) return this.msgError('表单验证失败')
      // if (this.form.scores && this.form.scores.length > 0) {
      //   let reduceScore = 0
      //   this.form.scores.forEach(score => {
      //     reduceScore += score.scoreInput
      //   })
      //   this.businessScore.scoreInput = 100 + reduceScore
      //   // const level = judgeScoreLevel(this.businessScore.levelStdd, this.businessScore.scoreInput)
      //   // this.businessScore.scoreResult = judgeScoreResult(this.businessScore.resultStdd, level)
      //   // this.businessScore.scoreLevel = level
      //   this.businessScore.scoreLevel = matchingRule({rule: this.businessScore.levelStdd, value: this.businessScore.scoreInput})
      //   this.businessScore.scoreResult = matchingRule({rule: this.businessScore.resultStdd, value: this.businessScore.scoreInput})
      //   this.form.scores.push({...this.businessScore})
      // }
      this.form.scores = this.$refs.listScoreRef.getData()
      if (this.form.scores && this.form.scores.length < 2) {
        this.$message.info('请添加检查项')
        return
      }
      const opt = { ...this.form }
      if (opt.constructionId && opt.constructionId instanceof Array) {
        opt.constructionId = opt.constructionId.join(',')
      }
      if (!this.rdcTypeList.length) opt.rdcType = ''
      if (opts?.isRepeatEntry) opt.isRepeatEntry = opts.isRepeatEntry

      if (this.isEdit) {
        this.markRemovedScores(opt)
      } else {
        // opt.versionId = ''
        opt.versionCode = cfgInfo.versionCode
        opt.chkitemCode = cfgInfo.chkitemCode
        // opt.landparcelId = ''
        // opt.projectType = ''
        // opt.deliveryTypes = ''
      }

      this.btnLoading = true
      const res = await saveScores(opt).catch(() => false)
      this.btnLoading = false
      if (res === false) return

      // 已有相似的数据
      if (res.data?.isRepeatEntry === 'duplicate') return this.$refs.SimilarDataConfirm.open({ cfgInfo, data: res.data })

      this.msgSuccess('保存成功')
      this.show = false
      this.$emit('ok')
    },
    markRemovedScores(data) {
      // 标记移除的检查项
      const oldScores = this.evalScore.scores || []
      if (!oldScores.length) return

      const newScores = JSON.parse(JSON.stringify(data.scores || []))
      const scoreIds = newScores.map(i => i.chkitemScoreId).filter(i => i)
      oldScores.map(i => {
        if (scoreIds.includes(i.chkitemScoreId)) return
        newScores.push({ ...i, isDelete: 1 })
      })
      data.scores = newScores
    }
  }
}
</script>
<style lang="scss" scoped>
  .optimized-select {
    width: 100%;
    & /deep/.el-select__tags {
      white-space: nowrap;
      overflow: hidden;
      flex-wrap: nowrap;
      .el-tag--info {
        max-width: 70%;
      }
    }
  }
</style>
